export function filterMenuBySelectedKeys(menuData, selectedKeys) {
  const simplifiedSet = preprocessSelectedKeys(selectedKeys);
  return filterMenu(menuData, simplifiedSet);
}

function preprocessSelectedKeys(selectedKeys) {
  // 按长度排序
  const sortedKeys = selectedKeys.slice().sort((a, b) => a.length - b.length);
  const simplifiedSet = new Set();
  for (const key of sortedKeys) {
    // 获取父路径：去掉最后一部分
    const lastDashIndex = key.lastIndexOf('-');
    if (lastDashIndex === -1) {
      simplifiedSet.add(key);
      continue;
    }
    const parentKey = key.substring(0, lastDashIndex);
    if (simplifiedSet.has(parentKey)) {
      continue;
    }
    simplifiedSet.add(key);
  }
  return simplifiedSet;
}

function filterMenu(menuData, selectedKeysSet) {
  const result = [];
  menuData.forEach((node, index) => {
    const pathPrefix = `0-${index}`;
    const filteredNode = filterNode(node, pathPrefix, selectedKeysSet);
    if (filteredNode !== null) {
      result.push(filteredNode);
    }
  });
  return result;
}

function filterNode(node, pathPrefix, selectedKeysSet) {
  if (selectedKeysSet.has(pathPrefix)) {
    return { ...node };
  }

  if (node.children && Array.isArray(node.children)) {
    const filteredChildren = [];
    node.children.forEach((child, childIndex) => {
      const childPath = `${pathPrefix}-${childIndex}`;
      const filteredChild = filterNode(child, childPath, selectedKeysSet);
      if (filteredChild !== null) {
        filteredChildren.push(filteredChild);
      }
    });
    if (filteredChildren.length > 0) {
      return {
        ...node,
        children: filteredChildren
      };
    }
  }

  return null;
}